<template>
  <basic-dialog :visible="show"
                title="工单修正"
                min-width="700px"
                isShowClose
                @close="$emit('close')"
                :isShowInnerLoading = 'loading'>
    <q-toolbar class="tab">
      <q-tabs v-model="tab"
              shrink stretch dense
              inline-label
              align="left"
              active-color="primary"
              indicator-color="primary"
      >
        <q-tab name="count"  label="产量修正" />
        <q-tab name="time"  label="工时修正" />
      </q-tabs>
    </q-toolbar>
    <q-separator class="line"/>
    <q-form @reset="reset" @submit="submit" v-show="tab === 'count'" class="dialog-content" greedy>
      <div class="flex justify-between" style="padding: 20px 20px 0">
        <div class="flex justify-between full-width">
          <q-select
            style="display: inline-flex; min-width: 265px;max-width: 265px;padding-bottom: 20px"
            class="select order"
            outlined dense emit-value map-options options-dense
            :options="orderOptions"
            @input="checkinShifts"
            v-model="orderId"
          >
            <template v-slot:no-option>
              <div class="no-option" />
            </template>
            <template v-slot:before>
              <span class="text-red font-14">*</span>
              <span class="form-name font-14 text-black">加工产品：</span>
            </template>
          </q-select>
          <q-select
            style="display: inline-flex; min-width: 265px;padding-bottom: 20px"
            class="select order"
            outlined dense emit-value map-options options-dense
            :options="shiftOpt"
            @input="changeSelShift"
            v-model="shiftId"
          >
            <template v-slot:no-option>
              <div class="no-option" />
            </template>
            <template v-slot:before>
              <span class="text-red font-14">*</span>
              <span class="form-name font-14 text-black">加工班次：</span>
            </template>
          </q-select>
          <q-select
            style="width: 265px;padding-bottom: 20px"
            class="select order"
            outlined dense emit-value map-options options-dense
            :options="peopleOpt"
            placeholder="请选择加工人员"
            v-model="peopleId"
          >
            <template v-slot:no-option>
              <div class="no-option" />
            </template>
            <template v-slot:before>
              <span class="text-red font-14">*</span>
              <span class="form-name font-14 text-black">加工人员：</span>
            </template>
          </q-select>
          <div class="form-item inline-block" style="width: 267px">
            <span class="text-red">*</span><span class="form-name form-name font-14 text-black" style="margin-left: 2px;padding-right: 6px;width: 77px">填报日期：</span>
            <date-picker
              v-model="day"
              type="date"
              :range="false"
              :clearable="false"
              :editable="false"
              style="width: 180px"
              :disabled-date="disabledAfterToday"
              :rules="val => (val && val.length > 0) || '不能为空'"
              format="YYYY-MM-DD"
              placeholder="请选择填报日期"/>
          </div>
        </div>
        <div class="full-width justify-between flex">
          <div class="text-black" style="width: 265px;margin-left: 8px;line-height: 32px">
            报工数量：{{checkinCount}}
          </div>
          <q-input
            style="width: 265px"
            ref="jobCount"
            v-model="form.count"
            dense
            outlined
            :rules="[
              val =>  /^(-?\d+)(\.\d+)?$/.test(val) || '录入数据不合法',
              val => Number(val) != 0 || '修正产量不能为0',
              val => /^-?\d+?$/.test(val) || '只能输入整数',
              val => judgeCount(val) || '修正产量会导致当班产量超限',
              val => judgeOffset(val) || '修正产量会导致当班产量为负',
              val => judgeCount2(val) || '修正后数量不能低于质检数量',
            ]"
          >
            <template v-slot:before >
              <label class="text-right" style="font-size: 14px;color: #333">
                <span class="text-red">*</span>
                <span>修正数量：</span>
              </label>
            </template>
          </q-input>
        </div>
        <div class="full-width" style="padding-left: 8px">
          <q-input style="width: 100%" outlined v-model="remark" type="textarea" counter autogrow maxlength="100">
            <template v-slot:before>
              <label class="text-right name full-width" style="font-size: 14px">备注:</label>
            </template>
          </q-input>
        </div>
      </div>
      <q-separator />
      <div class="dialog-footer text-center margin-t-10">
        <q-btn outline label="取消" color="primary" @click="$emit('close')" class="q-mr-md"/>
        <q-btn unelevated label="确认" color="primary" type="submit" :disable="orderId === null"/>
      </div>
    </q-form>
    <div class="padding-t-20" v-show="tab === 'time'">
      <correction-time ref="correctionTime" @showLoading="loading = true" @hideLoading="loading = false"/>
    </div>
  </basic-dialog>
</template>

<script>
import { checkinShifts, getOrderDetail } from 'src/boot/job/process-order'
import correctionTime from './work-order/correction-time'
import moment from 'moment'
const disabledAfterToday = (date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date > today
}
export default {
  name: 'work-order-correction-quantity',
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  components: {
    correctionTime
  },
  data () {
    return {
      tab: 'count',
      loading: false,
      checkinCount: 0, // 所选班制报工数量
      checkinCountOpt: {},
      qualityCountObj: {}, // 班制质检数量
      qualityCount: 0, // 所选班制质检数量
      operatorsObj: {},
      shiftOpt: [],
      shiftId: null, // 选择班制
      peopleOpt: [],
      peopleId: '',
      form: {
        count: 1
      },
      orderOptions: [],
      orderId: null,
      remark: '',
      day: null,
      disabledAfterToday: disabledAfterToday
    }
  },
  watch: {
    tab: {
      immediate: true,
      handler: function (val) {
        val === 'time' && this.$refs.correctionTime.getList(this.form.id)
      }
    },
    shiftId: {
      immediate: true,
      handler: function (val) {
        if (val) {
          const operators = this.operatorsObj[val]
          if (operators && operators.length > 0) {
            this.peopleOpt = operators.map(item => {
              return {
                label: item.name,
                value: item.id
              }
            })
            this.peopleId = operators[0].id
          } else {
            this.peopleOpt = []
            this.peopleId = ''
          }
        }
      }
    }
  },

  methods: {
    // 编辑填充表格
    assignment (val) {
      this.tab = 'count'
      this.remark = ''
      this.form = Object.assign(this.form, val[0])
      this.loading = true
      this.day = new Date(new Date())
      if (this.form.isCombinedWorkOrder) {
        this.orderId = null
        this.getDetail(this.form.id)
      } else {
        console.log(this.form, '1111')
        if (this.form.qcStatus === this.Enums.BUSINESS_STATUS.CLOSE.value) {
          this.orderId = null
          this.shiftId = null
          this.checkinCount = 0
          this.checkinCountOpt = {}
          this.operatorsObj = {}
          this.qualityCountObj = {}
          this.loading = false
        } else {
          this.orderId = this.form.id
          this.orderOptions = [{
            label: this.form.materialNames[0],
            value: this.form.id
          }]
          this.checkinShifts()
        }
      }
    },
    // 获取工单详细
    getDetail (id) {
      getOrderDetail(id).then(res => {
        const workOrders = res.workOrders.filter(i => i.qcStatus !== this.Enums.BUSINESS_STATUS.CLOSE.value)
        this.orderOptions = workOrders.map(item => {
          return {
            label: `${this.$utils.label(item.materialName)}(${this.$utils.label(item.materialNumber)})`,
            value: item.id
          }
        })
        if (workOrders.length) {
          this.orderId = workOrders[0].id
          this.checkinShifts()
        } else {
          this.orderId = null
          this.shiftId = null
          this.checkinCount = 0
          this.checkinCountOpt = {}
          this.operatorsObj = {}
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取报工班制
    checkinShifts () {
      this.form.count = 1
      checkinShifts(this.orderId).then(res => {
        const checkinCountOpt = {}
        const operatorsObj = {}
        const qualityCountObj = {}
        if (res.data.length) {
          this.shiftOpt = res.data.map(item => {
            checkinCountOpt[item.id] = item.checkinCount
            operatorsObj[item.id] = item.operators
            qualityCountObj[item.id] = item.qualityCount
            return {
              label: item.name,
              value: item.id
            }
          })
          this.shiftId = res.data[0].id
          this.checkinCount = res.data[0].checkinCount
        } else {
          this.shiftId = null
          this.checkinCount = 0
        }
        this.checkinCountOpt = checkinCountOpt
        this.operatorsObj = operatorsObj
        this.qualityCountObj = qualityCountObj
      }).finally(() => {
        this.loading = false
      })
    },
    // 切换班制
    changeSelShift (e) {
      this.checkinCount = this.checkinCountOpt[e]
      this.$refs.jobCount.validate()
    },

    // 提交表单
    submit () {
      const index = this.peopleOpt.findIndex(item => item.value === this.peopleId)
      const obj = this.peopleOpt[index]
      const params = {
        id: this.orderId,
        count: this.form.count,
        shiftId: this.shiftId,
        operatorName: obj.label,
        day: moment(this.day).format('YYYY-MM-DD'),
        operatorId: this.peopleId,
        remark: this.remark
      }
      if (!this.shiftId || this.operatleId) return
      this.loading = true
      this.$emit('submit', params)
    },

    reset () {
      this.form.count = 1
      this.shiftId = null
    },
    hideLoading () {
      this.loading = false
    },

    // 校验修正数量
    judgeOffset (val) {
      let ret = false
      Number(val) + Number(this.checkinCount) >= 0 ? ret = true : ret = false
      return ret
    },

    // 校验修正数量
    judgeCount (val) {
      let ret = false
      Number(val) + Number(this.checkinCount) > 99999.9 ? ret = false : ret = true
      return ret
    },

    judgeCount2 (val) {
      if (val < 0) {
        const qualityCount = this.qualityCountObj[this.shiftId] ? this.qualityCountObj[this.shiftId] : 0
        return val >= qualityCount - this.checkinCount
      }
      return true
    }
  }
}
</script>

<style scoped lang="stylus">
  /deep/ .q-select__dropdown-icon {
    width 24px
    height 24px
    font-size 24px
    color rgba(0, 0, 0, .54)
  }
  .col-3{
    padding 0 10px
    margin-bottom 10px
  }
  .order{
    >>>.q-field__control-container{
      span{
        display: block;
        word-break: keep-all;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width 127px
      }
    }
  }
</style>
